package socket;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-29
 * Time: 14:46
 */

public class UdpEchoClient {
    //大前提
    DatagramSocket socket = null;
    //但是要明确服务器的地址 IP + port
    public String serverIP;
    public int serverPort;

    //客户端的构造方法 系统自己分配
    public UdpEchoClient (String IP,int port) throws SocketException {
        socket = new DatagramSocket();
        serverIP = IP;
        serverPort = port;
    }

    //启动客户端 从控制台中获取数据
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入内容: ");
            String request = scanner.next();
            //将输入的内容打包成DatagramPacket对象
            //这里的细节在于 将字符串 转为对象的时候 request.getBytes().length 获取的是有效字节的长度  而不是request.length
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //要有一个空的Packet对象接收返回的信息
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
            System.out.println(request+ " | " +response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
